package com.cqc.jdk8.Jutil.stream;

import com.cqc.eb.DeptEB;
import com.cqc.eb.UserEB;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author cui
 * @date 2025-02-21
 * @description  flatMap方法的主要目的是将复杂结构（如列表的列表）“展平”为单一流。
 **/
public class FlagMapTest {

    List<UserEB> userEBList1 = null;

    @Before
    public void before() {
        userEBList1 = getUserList1();
    }

    /**
     * flatMap 入参是原来的元素，出参是stream
     */
    @Test
    public void flatMap() {
        List<String> list = Arrays.asList("A,B,C", "1,2,3");
        List<String> resultList = list.stream()
                .flatMap(x -> {
                    String[] arr = x.split(",");
                    Stream<String> stream = Arrays.stream(arr);
                    return stream;
                }).collect(Collectors.toList());
        System.out.println(resultList);
    }

    /**
     * lambada写法
     */
    @Test
    public void flatMap2() {
        List<String> list = Arrays.asList("A,B,C", "1,2,3");
        list.stream()
                .flatMap(x-> Arrays.stream(x.split(",")))
                .forEach(System.out::println);
    }
    @Test
    public void flatMap3() {
        List<UserEB> userEBList1 = new ArrayList<>();
        UserEB a = new UserEB("张三", 10);
        UserEB b = new UserEB("李四", 11);
        userEBList1.add(a);
        userEBList1.add(b);

        List<UserEB> userEBList2 = new ArrayList<>();
        UserEB c = new UserEB("王五", 10);
        userEBList2.add(c);

        List<DeptEB> deptEBList = new ArrayList<>();
        deptEBList.add(new DeptEB("研发部",userEBList1));
        deptEBList.add(new DeptEB("法律部",userEBList2));

        List<UserEB> userEBList = deptEBList.stream()
                .flatMap(deptEB -> deptEB.getUserEBList().stream())
                .collect(Collectors.toList());
        System.out.println(userEBList);
    }


    private static List<UserEB> getUserList1() {
        List<UserEB> list = new ArrayList<>();
        UserEB w = new UserEB("w", 10);
        UserEB x = new UserEB("x", 11);
        UserEB y = new UserEB("y", 12);
        list.add(w);
        list.add(x);
        list.add(y);
        return list;
    }
}
